package cn.wjssl.domain.activity.service.quota.rule.impl;

import cn.wjssl.domain.activity.model.entity.ActivityCountEntity;
import cn.wjssl.domain.activity.model.entity.ActivityEntity;
import cn.wjssl.domain.activity.model.entity.ActivitySkuEntity;
import cn.wjssl.domain.activity.model.valobj.ActivitySkuStockKeyVO;
import cn.wjssl.domain.activity.repository.IActivityRepository;
import cn.wjssl.domain.activity.service.armory.IActivityDispatch;
import cn.wjssl.domain.activity.service.quota.rule.AbstractActionChain;
import cn.wjssl.types.enums.ResponseCode;
import cn.wjssl.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Author：lxd
 * @Description 库存校验
 * @Date：2025/2/19
 */

@Slf4j
@Component("activity_sku_stock_action")
public class ActivitySkuStockActionChain extends AbstractActionChain {

    @Resource
    private IActivityDispatch dispatch;

    @Resource
    private IActivityRepository repository;

    @Override
    public boolean action(ActivitySkuEntity activitySkuEntity, ActivityEntity activityEntity, ActivityCountEntity activityCountEntity) {
        log.info("活动责任链-商品库存处理【有效期、状态、库存(sku)】开始。sku:{} activityId:{}", activitySkuEntity.getSku(), activityEntity.getActivityId());
        // dispatch 定义的扣减库存方法
        boolean status = dispatch.subtractionActivitySkuStock(activitySkuEntity.getSku(), activityEntity.getEndDateTime());
        if (status) {
            // 如果库存扣减成功, 就把activitySkuEntity实体, 往redis延迟队列里推, 让定时任务同步数据库
            repository.activitySkuStockConsumeSendQueue(ActivitySkuStockKeyVO.builder()
                    .sku(activitySkuEntity.getSku())
                    .activityId(activityEntity.getActivityId())
                    .build());

            // 库存校验通过返回true
            return true;
        }

        // 如果库存校验失败, 那就报异常
        throw new AppException(ResponseCode.ACTIVITY_SKU_STOCK_ERROR.getCode(), ResponseCode.ACTIVITY_SKU_STOCK_ERROR.getInfo());
    }
}
